package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbOperator.AdvancedOperation;
import dbOperator.BasicOperation;

/**
 * Servlet implementation class AddBook
 */
@WebServlet("/Book")
public class Book extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**这个函数根据参数判断是哪一个页面发来的请求，调用相应的函数对book进行操作
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws ServletException
	 * @throws IOException
	 * makisemirai注释
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int type = Integer.parseInt(request.getParameter("Type2"));
		try {
		switch(type) {
		case 1:{addBook(request, response);break;}
		case 2:{editBook(request, response);break;}
		case 3:{addSpecificBook(request, response);break;}
		case 4:{editSpecificBook(request, response);break;}
		case 5:{deleteSpecificBook(request, response);break;} }
		}	catch (SQLException e) {
		e.printStackTrace();} 
		//去掉下一行代码以令弹框正常显示
		//response.sendRedirect(request.getHeader("Referer"));
	}

     /**此函数用于添加某一种书
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 * makisemirai注释
	 */
	public void addBook(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		Cookie cookies[] = request.getCookies();
		if (cookies == null) {
			response.sendRedirect("index.html");
			return;
		}
		for (Cookie c : cookies) {
			if (c.getName().equals("LoginInfo")) {
				String currentCookie = c.getValue();
				Connection con = BasicOperation.getConnection();
				int uid = AdvancedOperation.getUidbyCookie(con, currentCookie);
				if (AdvancedOperation.getIdentity(con, uid) != 2)
					return;
				String name = request.getParameter("Name");
				String category = request.getParameter("Category");
				String author = request.getParameter("Author");
				String ISBN = request.getParameter("ISBN");
				String publisher = request.getParameter("Publisher");
				String pricestr=request.getParameter("Price");
				if(pricestr.equals(""))return;
				Double price = Double.valueOf(pricestr);
				if(price<0)return;
				Statement sql = con.createStatement();
				if(!(ISBN==null||ISBN.equals(""))) 
				sql.executeUpdate("insert into Book(name,category,author,publisher,ISBN,price) values('" + name + "','" + category + "','" + author + "','" + publisher + "','" + ISBN + "','" + price + "')");
				else sql.executeUpdate("insert into Book(name,category,author,publisher,price) values('" + name + "','" + category + "','" + author + "','" + publisher + "','" + price + "')");
				response.getWriter().println("<script>alert('Add book successfully!');window.location.href='" + request.getHeader("Referer") + "'</script>");
                con.close();
				return;
			}
		}
	}

	/**此函数用于编辑某一种书的信息，根据bid定位
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 * makisemirai注释
	 */
	public void editBook(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		Cookie cookies[] = request.getCookies();
		if (cookies == null) {
			response.sendRedirect("index.html");
			return;
		}
		for (Cookie c : cookies) {
			if (c.getName().equals("LoginInfo")) {
				String currentCookie = c.getValue();
				Connection con = BasicOperation.getConnection();
				int uid = AdvancedOperation.getUidbyCookie(con, currentCookie);
				if (AdvancedOperation.getIdentity(con, uid) != 2)
					return;
				String bidstr = request.getParameter("eBID");
				String category = request.getParameter("category");
				String pricestr = request.getParameter("price");
				if (bidstr == null || pricestr.equals(""))
					return;
				Double price = Double.valueOf(pricestr);
				if(price<0)return;
				int bid = Integer.parseInt(bidstr);
				Statement sql = con.createStatement();
				sql.executeUpdate("update Book set category='" + category + "',price='" + price + "' where bid=" + bid);
				response.getWriter().println("<script>alert('Edit book successfully!');window.location.href='" + request.getHeader("Referer") + "'</script>");
                con.close();
				return;
			}
		}
	}

	/**此函数用于添加某种书的副本数量，根据bid定位
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 * makisemirai注释
	 */
	public void addSpecificBook(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		Cookie cookies[] = request.getCookies();
		if (cookies == null) {
			response.sendRedirect("index.html");
			return;
		}
		for (Cookie c : cookies) {
			if (c.getName().equals("LoginInfo")) {
				String currentCookie = c.getValue();
				Connection con = dbOperator.BasicOperation.getConnection();
				int uid = AdvancedOperation.getUidbyCookie(con, currentCookie);
				String bidstr = request.getParameter("aBID");
				String numstr = request.getParameter("Number");
				if (bidstr == null || numstr.equals(""))
					return;
				int bid = Integer.parseInt(bidstr);
				int num = Integer.parseInt(numstr);
				AdvancedOperation.addBooksbybid(con, uid, bid, num);
				con.close();
			}
		}
	}

	/**此函数用于编辑某种书的具体副本的信息，根据bookID定位
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 * makisemirai注释
	 */
	public void editSpecificBook(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		Cookie cookies[] = request.getCookies();
		if (cookies == null) {
			response.sendRedirect("index.html");
			return;
		}
		for (Cookie c : cookies) {
			if (c.getName().equals("LoginInfo")) {
				String currentCookie = c.getValue();
				Connection con = dbOperator.BasicOperation.getConnection();
				int uid = AdvancedOperation.getUidbyCookie(con, currentCookie);
				if (AdvancedOperation.getIdentity(con, uid) != 2)
					return;
				String bookID = request.getParameter("eBookID");
				String status = request.getParameter("Status");
				String floor = request.getParameter("floor");
				String shelf = request.getParameter("shelf");
				if (bookID == null)
					return;
				Statement sql = con.createStatement();
				sql.executeUpdate("update SpecificBook set status='" + status + "',position='" + floor + "-" + shelf
						+ "' where bookID='" + bookID + "'");
				con.close();
			}
		}
	}

	/**此函数用于删除某书的具体副本根据bookID定位
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 * makisemirai注释
	 */
	protected void deleteSpecificBook(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		Cookie cookies[] = request.getCookies();
		if (cookies == null) {
			response.sendRedirect("index.html");
			return;
		}
		for (Cookie c : cookies) {
			if (c.getName().equals("LoginInfo")) {
				String currentCookie = c.getValue();
				Connection con = dbOperator.BasicOperation.getConnection();
				int uid = AdvancedOperation.getUidbyCookie(con, currentCookie);
				String bookIDstr = request.getParameter("dBookID");
				String rsn = request.getParameter("reason");
				if (bookIDstr == null)
					return;
				AdvancedOperation.getBookDeleted(con, uid, bookIDstr, rsn);
				con.close();
			}

		}
	}
}
